package com.csea.common.service.impl;

import com.coze.openapi.client.workflows.run.RunWorkflowReq;
import com.coze.openapi.client.workflows.run.RunWorkflowResp;
import com.coze.openapi.service.service.CozeAPI;
import com.csea.common.config.CozeWorkflowIds;
import com.csea.common.converter.PublicIdiomConverter;
import com.csea.common.domain.dos.PublicIdiomDo;
import com.csea.common.service.CozeService;
import com.csea.common.utils.CozeUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Coze服务
 */
@Service
@Slf4j
public class CozeServiceImpl implements CozeService {
    @Autowired
    private CozeWorkflowIds cozeWorkflowIds;
    private final CozeAPI coze;

    @Autowired
    public CozeServiceImpl(CozeUtil cozeUtil) {
        this.coze = cozeUtil.getCozeAPI();
    }


    /**
     * 根据关键词解析成语
     * @param keyword 关键词
     * @return 成语
     * @author xiyou
     */
    @Override
    public PublicIdiomDo parseIdiomByCoze(String keyword) {
        String workflowId = cozeWorkflowIds.getIdiom();
        RunWorkflowReq req = buildRequest(Map.of("keyword", keyword), workflowId);
        RunWorkflowResp resp = executeApiCall(req, workflowId);
        if (resp == null || resp.getData() == null || resp.getCode() != 0) {
            return null;
        }
        return PublicIdiomConverter.convert(resp.getData());
    }


    /**
     * 构建请求
     * @param data 参数
     * @param workflowId 工作流ID
     * @return 请求
     * @author xiyou
     */
    private RunWorkflowReq buildRequest(Map<String,Object> data,String workflowId) {
        return RunWorkflowReq.builder()
                .workflowID(workflowId)
                .parameters(data)
                .build();
    }

    /**
     * 执行API调用
     * @param request 请求
     * @param workflowId 工作流ID
     * @return 响应
     * @author xiyou
     */
    private RunWorkflowResp executeApiCall(RunWorkflowReq request,String workflowId) {
        log.debug("调用Coze工作流 [ID: {}]", workflowId);
        return coze.workflows().runs().create(request);
    }
}
